<?php
defined('BASEPATH') OR exit('No direct script access allowed');
define("API_KEY", "api_key=00b65dd0bd0c670ae40041ff8dbed7c4");
define("API_SECRET", "&api_secret=3yr5hGP_W7_MvCu4T3ymDb7lIkUkm5bA");
define("ATTRIBUTE", "&attribute=glass,pose,gender,age,race,smiling");
define("DETECT_URL", "http://apicn.faceplusplus.com/v2/detection/detect?");
define("LANDMARK_URL", "http://api.faceplusplus.com/detection/landmark?");
define("COMPARE_URL", "https://apicn.faceplusplus.com/v2/recognition/compare?");
define("TYPE","&type=83p");//83点模式
define("MESSAGE_URL", "");//放回图文消息被点击需要跳转的地址，不需要跳转可不填

class Wehome extends CI_Controller {
	
	public function __construct(){

		parent::__construct();

		$this->load->library('CI_Wechat');

		$this->load->model('wxfans_model');
		$this->load->model('help_model');
		$this->load->model('wxconfig_model');

	}
	
	public function myewm($file_name){
		$this->load->view('ewm',array('filename'=>$file_name));
	}
	
	private function up_media($weObj,$openid){

		$filepath = WEBPATH.'imgpublic/';

		$_img_url = '';
		$logo = '';

		$user_file = 'user_'.$openid.'.jpg';

		if(!file_exists($filepath.$user_file)){


			$filename = 'ticket_ewm.jpg';

			$_img_url = $filepath.$filename;

			if(!file_exists($filepath.'logo_'.$openid.'.jpg')){

				$wx_user = $this->wxfans_model->get(array('openid'=>$openid));
				$wxinfo = json_decode($wx_user['wxinfo'],TRUE);
				$imgdata = file_get_contents($wxinfo['headimgurl']);

				$filename = 'logo_'.$openid.'.jpg';
				
				$fp = @fopen($filepath.$filename, "w");
				@fwrite($fp, $imgdata);
				fclose($fp);

			}

			$logo = $filepath.'logo_'.$openid.'.jpg';
			$card_path = $filepath.'newcard.jpg';
			$hei_path = $filepath.'hei.ttf';
			$uinfo =  $this->wxfans_model->get(array('openid'=>$openid));
			$wxinfo = json_decode($uinfo['wxinfo'],TRUE);

			include_once (WEBPATH.'application/libraries/ThinkImage/ThinkImage.class.php' );

			$user_pic = $filepath.$user_file;


			$img = new ThinkImage(THINKIMAGE_GD, $card_path); 

			if(!empty($logo)){$img->open($logo)->thumb(130, 130)->save($logo);}

			if(!empty($logo)){
				$img->open($card_path)->water($logo, array('40','28'))->text($wxinfo['nickname'],$hei_path,'22','#ffffff', array('262','42'))->text($uinfo['id'],$hei_path,'20','#FF4500', array(230,430))->text($uinfo['id'],$hei_path,'22','#ffffff', array(235,730))->save($user_pic);
			}

		}

		
		$user_file = $filepath.$user_file;
		
		$data['media'] = "@$user_file";
		$res = $weObj->uploadMedia($data,'image');

		$media_id = $res['media_id'];

		$data = array();

		$data = array(
			'media_id'=>$media_id,
			'media_endtime'=>time()+24*3600*2.8,
		);

		$res_code = $this->wxfans_model->upd($data,array('openid'=>$openid));

		return $media_id;

	}

	// get all subscribe user information
	public function init(){

		$wxconfig = $this->wxconfig_model->get(array('id'=>'1'));

		if(empty($wxconfig['init_flag'])){

			$weObj = new CI_Wechat();
			
			$all_user = $weObj->getUserList();
			$all_openid = $all_user['data']['openid'];
			$i = 1;
			$str = '';
			foreach ($all_openid as $k => $v) {

				$user = array();

				$wxinfo = $weObj->getUserInfo($v);
				$user['openid'] = $v;
				$user['wxinfo'] = json_encode($wxinfo);
				$user['help_del'] = '0';
				$user['sub_time'] = $wxinfo['subscribe_time'];

				$this->wxfans_model->add($user);
				if(($i % 5 == 0)){
					echo $str.'.';
				}else{
					$str = '';
				}
				
			}

		}

		echo 'SUCCESS!';

	}

	public function index(){
		
		$weObj = new CI_Wechat();
		$weObj->valid();
		$type = $weObj->getRev()->getRevType();

		switch ($type) {

			case Wechat::MSGTYPE_TEXT :

				$key = $weObj->getRev()->getRevContent();
				
				if($key === 'ceshi'){
					// $openid = $weObj->getRevFrom();
					// $uinfo = $this->wxfans_model->get(array('openid'=>$openid));
					// $weObj->text('test!!!!')->reply();
					// $media_id = $this->up_media_test($weObj,$openid);
					// $weObj->getRev()->image($media_id)->reply();
					
					// $weObj->text('<a href = "http://dfx.fxmyx.cn/index.php/wehome/myewm">TEST</a>')->reply();

					
					$filepath = WEBPATH.'imgpublic/'.'sy.jpg';
					$data['media'] = "@$filepath";
					$res = $weObj->uploadForeverMedia($data,'image');
					$media_id = $res['media_id'];

					$weObj->text($media_id)->reply();
					
					
				}elseif($key === '18805495554' || $key === 'lqsn' || $key === 'xzxm' || $key === 'sysd' || $key === 'xzzx'){

					

					$openid = $weObj->getRevFrom();
					$uinfo = $this->wxfans_model->get(array('openid'=>$openid));

					$all_user = $this->wxfans_model->ct(array('help_id'=>$uinfo['id'],'help_del'=>'0'));
					$text = '';

					if($all_user<30){
						$text = '您好，共有'.$all_user.'人帮您，距离领取纪念币还有'.(30-intval($all_user)).'个帮忙!';

						if(count($all_user) !== 0)
						{
							foreach ($all_user as $k => $v) {

								$t_wxinfo = json_decode($v['wxinfo'],TRUE);
								$t_nickname = $t_wxinfo['nickname'];
								$text .= "/拥抱$t_nickname/拥抱\n";
							}
						}

					}elseif($uinfo['have_get'] === '1'){
						$text = '对不起，你已经领取了'.$uinfo['hb_ct'].'枚纪念币，不能再次领取！';
					}else{
						$get_ct = floor($all_user/30);
						$text = '恭喜您获得'.$get_ct.'枚狗年限量版10元纪念币！告诉你的朋友，让他们也来领取吧！';
						$this->wxfans_model->upd(array('have_get'=>'1','hb_ct'=>$get_ct),array('openid'=>$openid));
					}

					$weObj->text($text)->reply();

				}elseif($key === '我的进度' || $key === '帮忙'|| $key === '进度'){

					

					$openid = $weObj->getRevFrom();
					$uinfo = $this->wxfans_model->get(array('openid'=>$openid));

					$all_user = $this->wxfans_model->gets(array('help_id'=>$uinfo['id'],'help_del'=>'0'));
					$text = '';

					if(count($all_user) < 30){
						$text = "您好，共有".count($all_user)."人帮您，距离领取纪念币还有".(30-count($all_user))."个帮忙！";
					}else{
						
						$text = "您好，共有".count($all_user)."人帮您，您可以领取".floor(count($all_user)/30)."枚限量纪念币！\n";

						foreach ($all_user as $k => $v) {

							$t_wxinfo = json_decode($v['wxinfo'],TRUE);
							$t_nickname = $t_wxinfo['nickname'];
							$text .= "/拥抱$t_nickname/拥抱\n";
						}

					}


					$weObj->text($text)->reply();exit;


				}

				elseif(is_numeric($key)){

					

					$openid = $weObj->getRevFrom();
					$uinfo = $this->wxfans_model->get(array('openid'=>$openid));

					$user = array();
			       	$openid = $weObj->getRevFrom();

			       	$wxinfo = $weObj->getUserInfo($openid);

					$user['openid'] = $openid;
					$user['wxinfo'] = json_encode($wxinfo);
					$user['help_del'] = '0';

					$uid = '';

					if(empty($uinfo['id'])){
						$user['sub_time'] = time();
						$uid = $this->wxfans_model->add($user,TRUE);
						$uinfo = $this->wxfans_model->get(array('openid'=>$openid));
					}

					$re_txt = '';

					if(!empty($uinfo)){

						// 帮助的人不存在
						$h_user = $this->wxfans_model->get(array('id'=>$key));
						$h_wxinfo = json_decode($h_user['wxinfo'],TRUE);

						if(empty($h_user)){
							$text = "您输入的编号不对，请和您的朋友核实后再输入！免费领狗年限量版10元纪念币活动正在进行，快来参加吧！";
							$weObj->text($text)->reply();exit;
						}


						// 是否已经帮助其他人
						if(!empty($uinfo['help_id'])){

							$help_u = $this->wxfans_model->get(array('id'=>$uinfo['help_id']));

							$help_wxinfo = json_decode($help_u['wxinfo'],TRUE);

							$help_nickname = $help_wxinfo['nickname'];

							$text = "抱歉，您已经帮【".$help_nickname."】，不能再次领取!免费领狗年限量版10元纪念币活动正在进行，快来参加吧！";
							$weObj->text($text)->reply();exit;

						}

						// 是否帮助自己
						if($key === $uinfo['id']){
							$re_txt = '抱歉，自己不能帮助自己哦~快喊朋友来帮助你';
							$weObj->text($re_txt)->reply();exit;
						}


						// 开始帮助
						$this->wxfans_model->upd(array('help_id'=>$key),array('openid'=>$openid));

						$text = $h_wxinfo['nickname']."谢谢你！你成功帮【".$h_wxinfo['nickname']."】领取了一枚限量版纪念币！\n【恭喜您刚刚获得了领取资格，快来领取吧！】";

						$data = array(
										'touser' => $openid,
										'msgtype' => 'text',
										'text' => array('content'=>$text)
									);

									$weObj->sendCustomMessage($data);

						    		$user_file = WEBPATH.'imgpublic/user_'.$openid.'.jpg';

						    		$media_id = '';

									if(!file_exists($user_file)){
										
										$media_id = $this->up_media($weObj,$openid);
									}elseif(empty($uinfo['media_id']) || time() > $uinfo['media_endtime']){
										$media_id = $this->up_media($weObj,$openid);
									}else{
										$media_id = $uinfo['media_id'];
									}

									$data = array(
										'touser' => $openid,
										'msgtype' => 'image',
										'image' => array('media_id'=>$media_id)
									);
									$weObj->sendCustomMessage($data);



					}

				}else{
					

					$weObj->text("您的输入有误，系统无法识别，免费领狗年限量版10元纪念币活动正在进行，快来参加吧！")->reply();
				}
				exit();
				break;
			case Wechat::MSGTYPE_EVENT :

				$eventype = $weObj->getRev()->getRevEvent ();

				
				if ($eventype ['event'] == "CLICK") {

					if($eventype ['key']=='MYHB'){

						       		$user = array();
						       		$openid = $weObj->getRevFrom();

						       		$uinfo = $this->wxfans_model->get(array('openid'=>$openid));
						       		$wxinfo = $weObj->getUserInfo($openid);

									$user['openid'] = $openid;
									$user['wxinfo'] = json_encode($wxinfo);
									$user['help_del'] = '0';

									$uid = '';

									if(empty($uinfo['id'])){
										$user['sub_time'] = time();
										$uid = $this->wxfans_model->add($user,TRUE);
									}else{
										$uid = $uinfo['id'];
										$user['resub_time'] = time();
										$user['help_del'] = '0';
										$this->wxfans_model->upd($user,array('openid'=>$openid));
									}

									$text = "您好，欢迎参加免费领狗年限量版10元纪念币活动！\n您的领取编号是：".$uid."\n怎么领取？\n1、把下面图片发给朋友；\n2、朋友进入后输入你的编号【".$uid."】\n凑30个帮忙，即可领取狗年限量版纪念币1枚！每人限2枚；【给朋友帮忙，直接输入他的编号即可】";

									$data = array(
										'touser' => $openid,
										'msgtype' => 'text',
										'text' => array('content'=>$text)
									);

									$weObj->sendCustomMessage($data);

						    		$user_file = WEBPATH.'imgpublic/user_'.$openid.'.jpg';

						    		$media_id = '';

									if(!file_exists($user_file)){
										
										$media_id = $this->up_media($weObj,$openid);
									}elseif(empty($uinfo['media_id']) || time() > $uinfo['media_endtime']){
										$media_id = $this->up_media($weObj,$openid);
									}else{
										$media_id = $uinfo['media_id'];
									}

									$data = array(
										'touser' => $openid,
										'msgtype' => 'image',
										'image' => array('media_id'=>$media_id)
									);
									$weObj->sendCustomMessage($data);

					}elseif($eventype ['key']=='MYP'){
						$openid = $weObj->getRevFrom();
						$uinfo = $this->wxfans_model->get(array('openid'=>$openid));

						if(empty($uinfo)){

							$weObj->text('您还未参加活动，请点击菜单"我要参加->参加活动"，获取专属编号后，再来查看')->reply();exit;

						}else{
							$all_user = $this->wxfans_model->gets(array('help_id'=>$uinfo['id'],'help_del'=>'0'));
							$text = '';

							if(count($all_user) < 30){
								$text = "您好，共有".count($all_user)."人帮您，距离领取纪念币还有".(30-count($all_user))."个帮忙！";

								if(count($all_user) !== 0)
								{
									foreach ($all_user as $k => $v) {

										$t_wxinfo = json_decode($v['wxinfo'],TRUE);
										$t_nickname = $t_wxinfo['nickname'];
										$text .= "/拥抱$t_nickname/拥抱\n";
									}
								}
							}else{
						
								$text = "您好，共有".count($all_user)."人帮您，您可以领取".floor(count($all_user)/30)."枚限量纪念币！\n";

								foreach ($all_user as $k => $v) {

									$t_wxinfo = json_decode($v['wxinfo'],TRUE);
									$t_nickname = $t_wxinfo['nickname'];
									$text .= "/拥抱$t_nickname/拥抱\n";
								}

							}


							$weObj->text($text)->reply();exit;
						}
					}elseif($eventype ['key']=='ADFX'){ // 费县
						$weObj->image('-Iwmnmc-DoYc4MRq1w07ce7_QKaLewlhslKooeTYyw8')->reply();
					}elseif($eventype ['key']=='ADLQ'){ // 梁邱
						$weObj->image('-Iwmnmc-DoYc4MRq1w07cdtZr2XuD3QzCdBfxzed53c')->reply();
					}elseif($eventype ['key']=='ADXZ'){ // 新庄
						$weObj->image('-Iwmnmc-DoYc4MRq1w07cfwg3FB0vgKKQv-Jb7mXGwQ')->reply();
					}elseif($eventype ['key']=='ADXXZ'){ // 薛庄
						$weObj->image('-Iwmnmc-DoYc4MRq1w07cVUJzAvoN-peRRE-oWeqKlU')->reply();
					}elseif($eventype ['key']=='ADSY'){ // 上冶
						$weObj->image('-Iwmnmc-DoYc4MRq1w07cV-wkio5PncOVjNJqx3lcQw')->reply();
					}
					// elseif($eventype['key'] == 'LQDD'){
					// 	$text = "领取地点：费县东方城西门服务台。原5元和币活动继续进行，15个领取不变。";
					// 	$weObj->text($text)->reply();exit;
					// }

		       }elseif ($eventype['event'] == "subscribe"){

					//关注事件，用户关注之后
		       		$user = array();
		       		$openid = $weObj->getRevFrom();

		       		$uinfo = $this->wxfans_model->get(array('openid'=>$openid));
		       		$wxinfo = $weObj->getUserInfo($openid);

					$user['openid'] = $openid;
					$user['wxinfo'] = json_encode($wxinfo);
					$user['help_del'] = '0';

					$uid = '';

					if(empty($uinfo['id'])){
						$user['sub_time'] = time();
						$uid = $this->wxfans_model->add($user,TRUE);
					}else{
						$uid = $uinfo['id'];
						$user['resub_time'] = time();
						$user['help_del'] = '0';
						$this->wxfans_model->upd($user,array('openid'=>$openid));
					}

					$text = "您好，欢迎参加免费领狗年限量版10元纪念币活动！\n您的领取编号是：".$uid."\n怎么领取？\n1、把下面图片发给朋友；\n2、朋友进入后输入你的编号【".$uid."】\n凑30个帮忙，即可领取狗年限量版纪念币1枚！每人限2枚；【给朋友帮忙，直接输入他的编号即可】";
					$tdata = array(
						'touser' => $openid,
						'msgtype' => 'text',
						'text' => array('content'=>$text)
					);

					ignore_user_abort(true);  
         			ob_start();
					$weObj->sendCustomMessage($tdata);
					header('Connection: close');  
					header('Content-Length: ' . ob_get_length());  
					ob_end_flush();  
					ob_flush();  
					flush();

		    		$user_file = WEBPATH.'imgpublic/user_'.$openid.'.jpg';

		    		$media_id = '';

					if(!file_exists($user_file)){
						
						$media_id = $this->up_media($weObj,$openid);
					}elseif(empty($uinfo['media_id']) || time() > $uinfo['media_endtime']){
						$media_id = $this->up_media($weObj,$openid);
					}else{
						$media_id = $uinfo['media_id'];
					}

					$data = array(
						'touser' => $openid,
						'msgtype' => 'image',
						'image' => array('media_id'=>$media_id)
					);
					
					$weObj->sendCustomMessage($data);exit;

				}elseif($eventype['event'] == "unsubscribe"){

					 $openid = $weObj->getRevFrom();

					$this->wxfans_model->upd(array('help_del'=>'1'),array('openid'=>$openid));


				}elseif($eventype['event'] == 'SCAN'){
					// $b = $eventype['eventkey'];
					// $weObj->text($b.'fff')->reply();
				}
				exit;
				break;

			case Wechat::MSGTYPE_VOICE :
				
				exit;
				break;

			case Wechat::MSGTYPE_IMAGE :
				
				exit;
				break;
			default :
				$weObj->text("help info")->reply();
		}



	}




	function curl_get_contents($url) {

		$ch = curl_init();  curl_setopt( $ch , CURLOPT_URL,$url);

		curl_setopt( $ch , CURLOPT_RETURNTRANSFER,1);

		curl_setopt( $ch , CURLOPT_TIMEOUT,1);

		curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT,1.5);

		$result = curl_exec($ch);

		return $result;

	}



	public function create_menu(){

		$newmenu =  array(
				"button"=>array(
					array('name'=>'我要参加','sub_button'=>array(
						array(
							'type' => 'view',
							'name' => '纪念币介绍',
							'url' => 'https://mp.weixin.qq.com/s?__biz=MzI0MDQxOTc3MA==&mid=2247488237&idx=6&sn=ce0facaee2fb57c1d59206d93c3ea683&chksm=e91a4438de6dcd2e54d59898c9b01e3d01a5e655b72c24b3303d80b0d40096011a2cbaaa307f&scene=0#rd'
						),
						array(
							'type' => 'click',
							'name' => '参加活动',
							'key' => 'MYHB'
						),

					)),
					array('type' => 'click','name' => '我的进度','key' => 'MYP'),
					array('name'=>'领取地点','sub_button'=>array(
						array(
							'type' => 'click',
							'name' => '费县',
							'key' => 'ADFX'
						),
						array(
							'type' => 'click',
							'name' => '梁丘',
							'key' => 'ADLQ'
						),
						array(
							'type' => 'click',
							'name' => '新庄',
							'key' => 'ADXZ'
						),
						array(
							'type' => 'click',
							'name' => '上冶',
							'key' => 'ADSY'
						),
						array(
							'type' => 'click',
							'name' => '薛庄',
							'key' => 'ADXXZ'
						),

					)),
					
				)
		);

		$weObj = new CI_Wechat();

		if($weObj->createMenu ($newmenu)){
			die('success');

		}else{
			die('fail');
		}
	}

}

